"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

from mod_python import apache
from mod_python import Session
from mod_python import util

from phunc import *
from phunc.cx_wrapper import db_tools
from phunc.logger import logger

# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage, showErr = error.genErrorPage, error.showErr
address = block.address
alt_location_choice = table.alt_location_choice

def index( req, **params ):
	"""displays a customer list and search box"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	page_params = {}
	broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
	flag = params.has_key('flag') and params['flag'] or 'customer'
	page_params = {'flag':flag}
	page_num=1
	if params.has_key('page') and params['page']:
			page_num = int(params['page'])
	sql_str = ''
	if flag=="customer":
			sql_str = "SELECT * FROM customer_info"
	if flag=="supplier":
			sql_str = "SELECT * FROM supplier_info"
	entity_type = params.has_key("entity_type") and params['entity_type'].strip() or None
	entity_name = params.has_key("entity_name") and params['entity_name'].strip() or None
	searchkey = params.has_key('searchkey') and params['searchkey'] or ''
	if entity_type:
		if "WHERE" in sql_str:
			sql_str = sql_str+" AND type='%s'"%entity_type.strip()
		else:
			sql_str = sql_str+" WHERE type='%s'"%entity_type.strip()
		page_params['entity_type'] = entity_type	       
	if entity_name:
		if "WHERE" in sql_str:
			sql_str = sql_str+" AND name LIKE '%%%s%%'"%entity_name.strip()
		else:
			sql_str = sql_str+" WHERE name LIKE '%%%s%%'"%entity_name.strip()
		page_params['entity_name'] = entity_name
	if searchkey.lower()!='all':
		if "WHERE" in sql_str:
			sql_str = sql_str+" AND lower(name) LIKE '%s%%'"%searchkey.lower()
		else:
			sql_str = sql_str+" WHERE lower(name) LIKE '%s%%'"%searchkey.lower()
		page_params['searchkey'] = searchkey		
	page_split_setup={
			'cursor':dbc,
			'sql':sql_str,
			'skin':page.session['skin'],
			'page':page_num,
			'pagesize':8,
			'url':"/bin/operations.py",
			'params':page_params
	}			
	business = table.ControlPage(**page_split_setup)
	page.content = {
		'results':business.result,
		'page_split':business.createHtml(),
		'index_list':utils.get_index_list(),
		'entitytypes':db_tools.exec_action(dbc,'get_entity_types'),
		'page_params':page_params
	}
	page.setup = {
			'breadcrumbs':['Operations'],
			'menu_title':'Operations Portal',
			'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
			'content_title':'Search',
			'broadcast_message':broadcast_message,
			'template':flag=='customer' and 'operations/o_customer.opt' or 'operations/o_supplier.opt'		      
	}
	page.info = {
			'query_string':info.query_string
	}
	return page.render()
				
#CREATE CUSTOMER
def create_customer_entity_type(req, **params):
	"""displays form 1 of 4 for creating a customer"""
	page = Page(req, company_db=True)
	entitytypes = db_tools.exec_action(page.company_db.cursor(),'get_entity_types')
	form_setup={
			'id':'customer',
			'action':'/bin/operations.py/create_customer_entity_details',
			'fieldsets':[{
					'id':None,
					'classid':'form',
					'legend':'Entity Type',			
					'items':[ 
							{'type':'select','label':'Customer is a','id':'entity_type','name':'entity_type','classid':'required','option':entitytypes,'option_value':{'split':None,'items':['id'],'default_value':''},'option_text':{'split':None,'items':['id'],'default_text':'-- Please select --'},'selected_type':2,'selected_value':'company','selected_key':None},				      
					]
			}],		      
			'template_dir':info.getTemplateDir(req),
			'form_bottom': {'type':'div','id':None,'classid':'bottom input','style':None,'items':[{'type':'submit','id':'submit','name':'submit','value':'Continue'}]},
	}
	uform = form.user_form(**form_setup)
	page.content = {
		'uform':uform,
		'entitytypes':entitytypes
	}
	page.setup = {
			'breadcrumbs':['operations', 'New Customer'],
			'menu_title':'Operations Portal',
			'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
			'content_title':'New Customer',
			'template':'operations/occ1.opt',
			'form':True
	}
	page.info = {
			'query_string':info.query_string
	}
	return page.render()

def create_customer_entity_details( req, **params ):
	"""displays form 2 of 4 for creating a customer"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	#billing_methods = [{'id':1,'name':'hard copy'},{'id':2,'name':'email'},{'id':3,'name':'fax'}]
	billing_methods = db_tools.exec_action(dbc,'get_billing_methods')
	SMTP_SERVER_OK=True
	for code_id in [info.THIS_EMAIL,info.SMTP_SERVER,info.SMTP_USER,info.SMTP_PASS]:
			code_value = db_tools.exec_action(dbc,'get_sys_code', paramlist = [code_id])
			if not code_value:
				SMTP_SERVER_OK=False
				break			
	exists_company_ids=db_tools.exec_action(dbc,'get_company_ids_from_customer')
	entities2=db_tools.exec_action(dbc,'get_company_entities',[params['entity_type']])
	form_action = '/bin/operations.py/create_customer_other_entity_billing'
	entities=[]
	if len(entities2)>0:
		if len(exists_company_ids)>0:
			for entity in entities2:
				flag=True
				for company_id in exists_company_ids:
					if company_id['company_id']!=None:
						if int(entity['id'].split(':')[0])==int(company_id['company_id']):
							flag=False
							break						
				if flag==True:
					entities.append(entity)
		else:
			entities=entities2
	if params['entity_type'] == 'person':
		exists_person_ids=db_tools.exec_action(dbc,'get_person_ids_from_customer')	  
		entities2=db_tools.exec_action(dbc,'get_person_entities',[params['entity_type']])
		form_action = '/bin/operations.py/create_customer_person_billing'
		entities=[]
		if len(entities2)>0:
			if len(exists_person_ids)>0:
				for entity in entities2:
					flag=True
					for person_id in exists_person_ids:
						if person_id['person_id']!=None:
							if int(entity['id'].split(':')[0])==int(person_id['person_id']):
								flag=False
								break							
					if flag==True:
						entities.append(entity)
			else:
				entities=entities2
	page.content={
		'billing_methods':billing_methods,
		'entities':entities,
		'lcase_entity_type':params['entity_type'].capitalize(),
		'entity_type':params['entity_type'],
		'form_action':form_action,
		'METHOD_ONE':info.BILLING_METHOD_ONE,
		'METHOD_TWO':info.BILLING_METHOD_TWO,
		'METHOD_THREE':info.BILLING_METHOD_THREE,
		'SMTP_SERVER_OK':SMTP_SERVER_OK,
		'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
	}
	page.setup = {
		'breadcrumbs':['operations', 'New Customer'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'New Customer',
		'template':'operations/occ2.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()

def create_customer_other_entity_billing(req, **params):
	"""displays form 3 of 4 for creating a customer"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	page.content = {
		'has_entity_id':False,
		'salesagents':db_tools.exec_action(dbc,'get_salesagents'),
		'params_name':params.keys(),
		'params_list':params,
		'METHOD_ONE':info.BILLING_METHOD_ONE,
		'METHOD_TWO':info.BILLING_METHOD_TWO,
		'METHOD_THREE':info.BILLING_METHOD_THREE
	}
	if params.has_key('entity_id') and params['entity_id'].strip():
		page.content['has_entity_id'] = True
		company_id = params['entity_id'].split(':')[0]
		page.content['billing_method'] = params['update_billing_method']
		if page.content['billing_method']==info.BILLING_METHOD_ONE:
			billing_address_choices = table.place_of_business_choice(dbc, str(company_id))
			page.content['billing_address_choices']=billing_address_choices
			if not billing_address_choices:
				validation_class = 'required'
			else:
				validation_class = 'validate-one-if-none'
		else:
			validation_class = 'required'
	else:
		page.content['billing_method'] = params['billing_method']
		validation_class = 'required'
	page.content['validation_class']=validation_class
	page.content['address']=address(validation_class)
	page.setup = {
		'breadcrumbs':['operations', 'New Customer'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'New Customer',
		'template':'operations/occ3.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()
		
def create_customer_person_billing( req, **params ):
	"""displays form 4 of 4 for creating a customer"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	page.content = {
		'salesagents':db_tools.exec_action(dbc,'get_salesagents'),
		'has_key':False,
		'alt_location_types':db_tools.exec_action(dbc,'get_alt_location_types'),
		'params_name':params.keys(),
		'params_list':params,
		'METHOD_ONE':info.BILLING_METHOD_ONE,
		'METHOD_TWO':info.BILLING_METHOD_TWO,
		'METHOD_THREE':info.BILLING_METHOD_THREE
	}
	validation_class = ''
	if params.has_key('entity_id') and params['entity_id']!='':			
		page.content['has_key']=True
		page.content['billing_method'] = params['update_billing_method']
		person_id = params['entity_id'].split(':')[0]
		if page.content['billing_method']==info.BILLING_METHOD_ONE:	
			billing_address_choices = alt_location_choice(dbc, str(person_id))
			page.content['billing_address_choices']=billing_address_choices
			if not billing_address_choices:
				validation_class = 'required'
			else:
				validation_class = 'validate-one-if-none'
		else:
			validation_class = 'required'
	else:
		page.content['billing_method'] = params['billing_method']
		validation_class = 'required'
	page.content['validation_class']=validation_class
	page.content['address']=address(validation_class)
	page.setup = {
		'breadcrumbs':['operations', 'New Customer'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer!','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'New Customer',
		'template':'operations/occ4.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()
		
def create_customer_submit( req, **params ):
	"""actually creates a customer -- redirects to operations index"""
	try:
		session = Session.Session(req)
		check_access(req,session, req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()		
		entity_type = params['entity_type']
		billing_method = None
		if params.has_key('entity_id') and params['entity_id']!='':
			# test whether it's a company_id or person_id and use it to get the actual entity_id
			billing_method = params['update_billing_method']
			company_or_person_id = params['entity_id'].split(':')[0]
			entity_id = company_or_person_id
			if params.has_key('update_abn') and params['update_abn']!='':
				abn = db_tools.exec_action(dbc,'get_if_exist_abn',[str(entity_id)])
				if abn:
					db_tools.exec_action(dbc,'update_abn',[params['update_abn'],str(entity_id)])
				else:
					db_tools.exec_action(dbc,'insert_abn',[str(entity_id),params['update_abn']])
		else:
			billing_method = params['billing_method']
			if entity_type == 'person':
				db_tools.exec_action(dbc,'insert_person',[params['surname'],params['given_name'],str(entity_type)])
			else:
				db_tools.exec_action(dbc,'insert_company',[params['name'],str(entity_type)])
			entity_id=db_tools.exec_action(dbc,'get_entity_id')[0]['id']
			# otherwise create an entity and return the entity_id
			if params.has_key('abn') and params['abn']!='':
				db_tools.exec_action(dbc,'insert_abn',[entity_id,params['abn']])
		if billing_method==info.BILLING_METHOD_ONE:#hard copy
			if params.has_key('place_of_business_id') and params['place_of_business_id']!='':
				# get the address_id (for the customer's billing address) from the selected place of business
				address_id= db_tools.exec_action(dbc,'get_address_id',[params['place_of_business_id']])[0]['address_id']
			elif params.has_key('alt_location_id') and params['alt_location_id']!='':
				# otherwise try to get it from the selected alt_location (remember if it's negative
				# it's actually the person_id so get the pob_id from system.person then the address for that pob)
				address_id= db_tools.exec_action(dbc,'get_address_id',[params['alt_location_id']])[0]['address_id']
			else:
				# otherwise create an address and return the address_id
				if params.has_key('line2') and params['line2']!='':
					db_tools.exec_action(dbc,'insert_address1',[params['line1'],params['line2'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
				else:
					db_tools.exec_action(dbc,'insert_address2',[params['line1'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
				address_id = db_tools.exec_action(dbc,'get_address_id4')[0]['id']
				if params.has_key('pob_name') and params['pob_name']!='':
					# also create place_of_business if possible
					other_possible_keys = ['pob_name', 'pob_phone', 'pob_fax']
					other_keys = []
					other_values = []
					for key in other_possible_keys:
						if params.has_key(key) and params[key]!='':
							other_keys = other_keys + [key]
							other_values = other_values + [params[key]]
					db_tools.exec_action(dbc,'insert_address3',[', '.join(other_keys).replace('pob_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
				elif params.has_key('al_type') and params['al_type']!='':
					# or alt_location if possible
					other_possible_keys = ['al_type', 'al_phone', 'al_fax']
					other_keys = []
					other_values = []
					for key in other_possible_keys:
						if params.has_key(key) and params[key]!='':
							other_keys = other_keys + [key]
							other_values = other_values + [params[key]]
					db_tools.exec_action(dbc,'insert_address3',[ ', '.join(other_keys).replace('al_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
				elif entity_type == 'person':
					# otherwise (if it's a person) call it a postal_address and be done with it
					db_tools.exec_action(dbc,'insert_address5',[str(entity_id),str(address_id)])		
			# create the customer record, with or without sales_agent info
			if params.has_key('sales_agent_id') and params['sales_agent_id']!='':
				db_tools.exec_action(dbc,'insert_customer1',[ str(entity_id),str(params['sales_agent_id']),billing_method,str(address_id)])
			else:
				db_tools.exec_action(dbc,'insert_customer2',[ str(entity_id),billing_method,str(address_id)])
		if billing_method==info.BILLING_METHOD_TWO:#email
			email = params['email']
			db_tools.exec_action(dbc,'insert_contact_detail',[ str(entity_id),info.CONTACT_TYPE_EMAIL,email])
			if params.has_key('sales_agent_id') and params['sales_agent_id']!='':
				db_tools.exec_action(dbc,'insert_customer3',[ str(entity_id),str(params['sales_agent_id']),billing_method])
			else:
				db_tools.exec_action(dbc,'insert_customer4',[ str(entity_id),billing_method])
		if billing_method==info.BILLING_METHOD_THREE:#fax
			fax = params['fax']
			db_tools.exec_action(dbc,'insert_contact_detail',[ str(entity_id),info.CONTACT_TYPE_FAX,fax])
			if params.has_key('sales_agent_id') and params['sales_agent_id']!='':
				db_tools.exec_action(dbc,'insert_customer3',[ str(entity_id),str(params['sales_agent_id']),billing_method])
			else:
				db_tools.exec_action(dbc,'insert_customer4',[ str(entity_id),billing_method])
		# get the customer_id and use it to create an accounts receivable account
		#customer_id = db_tools.exec_action(dbc,'get_customer_id',[str(dbc.lastrowid)])[0]['id']
		customer_id = db_tools.exec_action(dbc,'get_customer_id')[0]['id']
		#db_tools.exec_action(dbc,'insert_ledger_ar_chart_of_accounts',[str(customer_id)])
		nid = db_tools.exec_action(dbc,'get_next_ar_seq')[0]['id']
		db_tools.exec_action(dbc,'insert_ledger_ar_chart_of_accounts',[nid,str(customer_id)])		
		conn.commit()		
		broadcast_message='Customer created'
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,'/bin/operations.py?flag=customer&amp;broadcast_message=%s'%broadcast_message)		

#CREATE SUPPLIER
def create_supplier_entity_type(req, **params):
	"""displays form 1 of 4 for creating a supplier"""
	page = Page(req, company_db=True)
	entitytypes = db_tools.exec_action(page.company_db.cursor(),'get_entity_types')
	form_setup={
		'id':'supplier',
		'action':'/bin/operations.py/create_supplier_entity_details',
		'fieldsets':[{
			'id':None,
			'classid':'form',
			'legend':'Entity Type',
			'items':[
				{'type':'select','label':'Supplier is a','id':'entity_type','name':'entity_type','classid':'required','option':entitytypes,'option_value':{'split':None,'items':['id'],'default_value':''},'option_text':{'split':None,'items':['id'],'default_text':'-- Please select --'},'selected_type':2,'selected_value':'company','selected_key':None},					
			]
		}],		      
		'template_dir':info.getTemplateDir(req),
		'form_bottom': {
			'type':'div',
			'id':None,
			'classid':'bottom input',
			'style':None,
			'items':[
				{'type':'submit','id':'submit','name':'submit','value':'Continue'},
			]
		},
	}
	uform = form.user_form(**form_setup)
	page.content = {
			'uform':uform,
			'entitytypes':entitytypes
	}
	page.setup = {
		'breadcrumbs':['operations', 'New Supplier'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
		'content_title':'New Supplier',
		'template':'operations/ocsu1.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()

def create_supplier_entity_details( req, **params ):
	"""displays form 2 of 4 for creating a supplier"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	entity_type = params['entity_type']
	exists_company_ids=db_tools.exec_action(dbc,'get_company_ids_from_supplier')
	entities2=db_tools.exec_action(dbc,'get_company_entities',[entity_type])
	form_action = '/bin/operations.py/create_supplier_other_entity_billing'	   
	entities=[]
	if len(entities2)>0:
		if len(exists_company_ids)>0:				
			for entity in entities2:
				flag=True
				for company_id in exists_company_ids:
					if company_id['company_id']!=None:
						if int(entity['id'].split(':')[0])==int(company_id['company_id']):
							flag=False
							break						
				if flag==True:
					entities.append(entity)
		else:
			entities=entities2
	if entity_type == 'person':
		exists_person_ids=db_tools.exec_action(dbc,'get_person_ids_from_supplier')	  
		entities2=db_tools.exec_action(dbc,'get_person_entities',[entity_type])   
		form_action = '/bin/operations.py/create_supplier_person_billing'
		entities=[]
		if len(entities2)>0:
			if len(exists_person_ids)>0:					
				for entity in entities2:
					flag=True
					for person_id in exists_person_ids:
						if person_id['person_id']!=None:
							if int(entity['id'].split(':')[0])==int(person_id['person_id']):
								flag=False
								break							
					if flag==True:
						entities.append(entity)
			else:
				entities=entities2
	page.content={
			'entities':entities,
			'lcase_entity_type':entity_type.capitalize(),
			'entity_type':entity_type,
			'form_action':form_action,
			'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
	}
	page.setup = {
		'breadcrumbs':['operations', 'New Supplier'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
		'content_title':'New Supplier',
		'template':'operations/ocsu2.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()
	
def create_supplier_other_entity_billing(req, **params):
	"""displays form 3 of 4 for creating a supplier"""
	page = Page(req, company_db=True)
	page.content = {
		'has_entity_id':False,
		'params_name':params.keys(),
		'params_list':params
	}
	if params.has_key('entity_id') and params['entity_id']!='':
		page.content['has_entity_id']=True
		company_id = params['entity_id'].split(':')[0]
		billing_address_choices = table.place_of_business_choice(page.company_db.cursor(), str(company_id))
		page.content['billing_address_choices']=billing_address_choices
		if billing_address_choices == '':
			validation_class = 'required'
		else:
			validation_class = 'validate-all-or-none'
	else:
		validation_class = 'required'
	page.content['validation_class']=validation_class
	page.content['address']=address(validation_class)
	page.setup = {
		'breadcrumbs':['operations', 'New Supplier'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
		'content_title':'New Supplier',
		'template':'operations/ocsu3.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string,
	}
	return page.render()
		
def create_supplier_person_billing( req, **params ):
	"""displays form 4 of 4 for creating a supplier"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	page.content = {
		'has_key':False,
		'alt_location_types':db_tools.exec_action(dbc,'get_alt_location_types'),
		'params_name':params.keys(),
		'params_list':params		
	}
	validation_class = ''
	if params.has_key('entity_id') and params['entity_id']!='':
		page.content['has_key']=True
		person_id = params['entity_id'].split(':')[0]
		billing_address_choices = alt_location_choice(dbc, str(person_id))
		page.content['billing_address_choices']=billing_address_choices
		if billing_address_choices == '':
			validation_class = 'required'
		else:
			validation_class = 'validate-all-or-none'
	else:
		validation_class = 'required'	 
	page.content['address']=address(validation_class)
	page.setup = {
		'breadcrumbs':['operations', 'New Supplier'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier!'],
		'content_title':'New Supplier',
		'template':'operations/ocsu4.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()

def create_supplier_submit( req, **params ):
	"""actually creates a supplier -- redirects to operations index"""
	try:
		session = Session.Session(req)
		check_access(req,session, req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()		
		entity_type = params['entity_type']
		if params.has_key('entity_id') and params['entity_id']!='':
			# test whether it's a company_id or person_id and use it to get the actual entity_id
			company_or_person_id = params['entity_id'].split(':')[0]
			entity_id = company_or_person_id
			if params.has_key('update_abn') and params['update_abn']!='':
				abn = db_tools.exec_action(dbc,'get_if_exist_abn',[str(entity_id)])
				if abn:
					db_tools.exec_action(dbc,'update_abn',[params['update_abn'],str(entity_id)])
				else:
					db_tools.exec_action(dbc,'insert_abn',[str(entity_id),params['update_abn']])
		else:
			if entity_type == 'person':
				db_tools.exec_action(dbc,'insert_person',[params['surname'],params['given_name'],str(entity_type)])
			else:
				db_tools.exec_action(dbc,'insert_company',[params['name'],str(entity_type)])
			entity_id=db_tools.exec_action(dbc,'get_entity_id')[0]['id']
			# otherwise create an entity and return the entity_id
			if params.has_key('abn') and params['abn']!='':
				db_tools.exec_action(dbc,'insert_abn',[entity_id,params['abn']]) 
		if params.has_key('place_of_business_id') and params['place_of_business_id']!='':
			# get the address_id (for the supplier's billing address) from the selected place of business
			address_id= db_tools.exec_action(dbc,'get_address_id',[params['place_of_business_id']])[0]['address_id']
		elif params.has_key('alt_location_id') and params['alt_location_id']!='':
			# otherwise try to get it from the selected alt_location (remember if it's negative
			# it's actually the person_id so get the pob_id from system.person then the address for that pob)
			address_id= db_tools.exec_action(dbc,'get_address_id',[params['alt_location_id']])[0]['address_id']
		else:
			# otherwise create an address and return the address_id
			if params.has_key('line2') and params['line2']!='':
				db_tools.exec_action(dbc,'insert_address1',[params['line1'],params['line2'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
			else:
				db_tools.exec_action(dbc,'insert_address2',[params['line1'],params['suburb'].lower(),params['region'].lower(),params['code'].lower(),params['country'].lower()])
			address_id = db_tools.exec_action(dbc,'get_address_id4')[0]['id']
			if params.has_key('pob_name') and params['pob_name']!='':
				# also create place_of_business if possible
				other_possible_keys = ['pob_name', 'pob_phone', 'pob_fax']
				other_keys = []
				other_values = []
				for key in other_possible_keys:
					if params.has_key(key) and params[key]!='':
						other_keys = other_keys + [key]
						other_values = other_values + [params[key]]
				db_tools.exec_action(dbc,'insert_address3',[', '.join(other_keys).replace('pob_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
			elif params.has_key('al_type') and params['al_type']!='':
				# or alt_location if possible
				other_possible_keys = ['al_type', 'al_phone', 'al_fax']
				other_keys = []
				other_values = []
				for key in other_possible_keys:
					if params.has_key(key) and params[key]!='':
						other_keys = other_keys + [key]
						other_values = other_values + [params[key]]
				db_tools.exec_action(dbc,'insert_address3',[ ', '.join(other_keys).replace('al_', '').replace('type','name'),str(entity_id),str(address_id),"', '".join(other_values)])
			elif entity_type == 'person':
				# otherwise (if it's a person) call it a postal_address and be done with it
				db_tools.exec_action(dbc,'insert_address5',[str(entity_id),str(address_id)])
		# create the supplier record
		db_tools.exec_action(dbc,'insert_supplier',[str(entity_id),str(address_id)])
		# get the customer_id and use it to create an accounts receivable account
		#supplier_id = db_tools.exec_action(dbc,'get_supplier_id',[str(dbc.lastrowid)])[0]['id']
		supplier_id = db_tools.exec_action(dbc,'get_supplier_id')[0]['id']
		nid = db_tools.exec_action(dbc,'get_next_ap_seq')[0]['id']
		db_tools.exec_action(dbc,'insert_ledger_ap_chart_of_accounts',[nid,str(supplier_id)])
		conn.commit()		
		broadcast_message='Supplier created'
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,'/bin/operations.py?flag=supplier&amp;broadcast_message=%s'%broadcast_message)		

def customer_page( req, **params ):
	"""displays an information page for a single customer"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	cid=params['cid']
	if cid==None:
		cid=1		
	page.content = {
		'customer_id':cid
	}
	customer_billing_info=db_tools.exec_action(dbc,'get_customer_billing_info',[int(cid)])
	if not customer_billing_info:
		raise GeneralBusinessErr('customer_not_exist','/bin/login.py/login_out')
	customer_billing_info = customer_billing_info[0]
	#get customer billing method
	billing_method = customer_billing_info['billing_method']
	page.content['billing_method'] = billing_method
	page.content['title']=customer_billing_info['customer_name']
	if billing_method==info.BILLING_METHOD_ONE:#hard copy
		billing_address = {
			'line1':customer_billing_info['line1'],
			'line2':customer_billing_info['line2'],
			'suburb':customer_billing_info['suburb'],
			'region':customer_billing_info['region'],
			'code':customer_billing_info['code'],
			'country':customer_billing_info['country']
		}
		page.content['customer_billing_address']=utils.get_formatted_address(billing_address,return_one_line=True)
	else:
		customer_billing_address=None
		if billing_method==info.BILLING_METHOD_TWO:#email
			customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_billing_info['entity_id'],info.CONTACT_TYPE_EMAIL])
		if billing_method==info.BILLING_METHOD_THREE:#fax
			customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_billing_info['entity_id'],info.CONTACT_TYPE_FAX])
		if not customer_billing_address:
			page.content['customer_billing_address'] = ''
		else:
			page.content['customer_billing_address'] = customer_billing_address[0]['detail']
	page.content['customer_salse_agent']=str(customer_billing_info["sales_agent"] or ' ')
	delivery_invoiceset = db_tools.exec_action(dbc,'get_delivery_invoices')
	for delivery_invoice in delivery_invoiceset:
		if delivery_invoice['method'] ==info.BILLING_METHOD_ONE:
			if delivery_invoice['address_id']:
				address_details = db_tools.exec_action(dbc,'get_address_info',[delivery_invoice['address_id']])
				if address_details:						
					delivery_invoice['detail'] = utils.get_formatted_address(address_details[0],return_one_line=True)
				else:
					raise genErrorPage('ADDRESS_NOT_EXISTS','/bin/login.py/login_out')
			else:
				raise genErrorPage('SYSTEM_ERROR','/bin/login.py/login_out')
		delivery_invoice['date']  = str(delivery_invoice['date'])[:10]
	page.content['delivery_invoiceset'] = delivery_invoiceset		
	
	#----------------------------#
	#------------invoice info--------------#
	#----------------------------#
	page_num = 1
	if params.has_key('page') and params['page']:
		page_num = int(params['page'])
	sql_str = "SELECT * FROM system.invoice_info where customer_id=%d ORDER BY id"%int(cid)
	split_page_setup={
		'cursor':dbc,
		'sql':sql_str,
		'skin':page.session['skin'],
		'page':page_num,
		'pagesize':8,
		'url':"/bin/operations.py/customer_page",
		'params':{'pid':cid}
	}			
	invoices = table.ControlPage(**split_page_setup)	    
	invoices_info = invoices.result
	page_split = invoices.createHtml()
	for invoice_info in invoices_info:
		invoice_info['date'] = str(invoice_info['date'])[:10]
	page.content['invoices_info']=invoices_info
	page.content['page_split'] = page_split
	page.setup = {
		'breadcrumbs':['operations','Customer Details - ' + customer_billing_info['customer_name']],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'Customer Details - ' + customer_billing_info['customer_name'],
		'broadcast_message':params.has_key('broadcast_message') and params['broadcast_message'] or None,
		'template':'operations/ocii.opt',
		'form':True,
	}
	page.info = {
		'query_string':info.query_string,
		'name':customer_billing_info['customer_name']
	}
	return page.render()

def supplier_page(req, **params):
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	pid=params['pid']
	if pid==None:
		pid=1
	page.content = {
		'has_billing_address':False
	}
	supplier_billing_info=db_tools.exec_action(dbc,'get_supplier_billing_info',[int(pid)])
	if len(supplier_billing_info)>0:
		page.content['has_billing_address']=True
		supplier_billing_info=supplier_billing_info[0]
		title=supplier_billing_info['supplier_name'] 
		page.content['title']=title
		billing_address = {
			'line1':supplier_billing_info['line1'],
			'line2':supplier_billing_info['line2'],
			'suburb':supplier_billing_info['suburb'],
			'region':supplier_billing_info['region'],
			'code':supplier_billing_info['code'],
			'country':supplier_billing_info['country']
		}
		page.content['supplier_billing_address']=utils.get_formatted_address(billing_address,return_one_line=True)
	#----------------------------#
	#------------purchase order info--------------#
	#----------------------------#
	page_num = 1
	if params.has_key('page') and params['page']:
		page_num = int(params['page'])
	sql_str = "SELECT * FROM system.purchase_order_info where supplier_id=%d ORDER BY id"%int(pid)
	split_page_setup={
		'cursor':dbc,
		'sql':sql_str,
		'skin':page.session['skin'],
		'page':page_num,
		'pagesize':8,
		'url':"/bin/operations.py/supplier_page",
		'params':{'pid':pid}
	}			
	purchase_orders = table.ControlPage(**split_page_setup)	    
	purchase_orders_info = purchase_orders.result
	page_split = purchase_orders.createHtml()
	for purchase_orders in purchase_orders_info:
		purchase_orders['date'] = str(purchase_orders['date'])[:10]
	page.content['purchase_orders_info']=purchase_orders_info
	page.content['page_split'] = page_split
	page.setup = {
		'breadcrumbs':['operations','Supplier Details - ' + title],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'Supplier Details - ' + title,
		'template':'operations/ocpi.opt'
	}
	page.info = {
		'query_string':info.query_string,
		'name':title
	}
	return page.render()

def insert_invoice( req,**params ):
	"""displays a form for creating an invoice"""
	import datetime
	page = Page(req, company_db=True)
	session = page.session
	dbc = page.company_db.cursor()
	broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''	
	#check the 'ar' account
	control = db_tools.exec_action(dbc,'get_coa2',['ar'])
	if not control:
		if broadcast_message:
			broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/insert_account?short_name=ar'>create</a> an Account(finance) with Subledger 'ar'." or "<br />You must create an Account(finance) with Subledger 'ar'."
		else:
			broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/insert_account?short_name=ar'>create</a> an Account(finance) with Subledger 'ar'." or "You must create an Account(finance) with Subledger 'ar'."			
	#check customers
	customers = db_tools.exec_action(dbc,'get_customers')
	if not customers:
		if broadcast_message:
			broadcast_message += "<br />You must <a href='/bin/operations.py/create_customer_entity_type'>create</a> some customers before you create an invoice."
		else:
			broadcast_message = "You must <a href='/bin/operations.py/create_customer_entity_type'>create</a> some customers before you create an invoice."		
	#check special accounts
	special_params = [{'param_id':'special_ac_comm_pay','param_name':'Commissions Payable','param_desc':'Commissions Payable'},{'param_id':'special_ac_sales_rev','param_name':'Sales Revenue','param_desc':'Sales Revenue'}]
	special_params_len = len(special_params)
	exist_special_params_len = db_tools.exec_action(dbc, 'exist_special_params_len', [tuple([a['param_id'] for a in special_params])])[0]['special_params_len']
	if special_params_len!=exist_special_params_len:
		if broadcast_message:
			broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice." or "<br />You must setup the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice."
		else:
			broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice." or "You must setup the Special accounts(Sales Revenue,Commissions Payable)(finance) before you create an invoice."
	#redirect
	if special_params_len!=exist_special_params_len or not customers or not control:
		util.redirect(req, '/bin/operations.py?broadcast_message=%s' % broadcast_message)
	#check tax list and default tax
	tax_list = db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail sale'])
	default_tax = db_tools.exec_action(dbc, 'get_default_tax')
	
	if not tax_list:
		if broadcast_message:
			broadcast_message += 'finance' in session['user_access'].values() and "<br />You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Sale)(finance) before you create an invoice." or "<br />You'd better setup the Tax accounts(Retail Sale)(finance) before you create an invoice."
		else:
			broadcast_message += 'finance' in session['user_access'].values() and "You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Sale)(finance) before you create an invoice." or "You'd better setup the Tax accounts(Retail Sale)(finance) before you create an invoice."			
	if not default_tax:
		if broadcast_message:
			broadcast_message += 'admin' in session['user_access'].values() and "<br />You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create an invoice." or "<br />You'd better setup the Default Tax(admin) before you create an invoice."
		else:
			broadcast_message += 'admin' in session['user_access'].values() and "You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create an invoice." or "You'd better setup the Default Tax(admin) before you create an invoice."
	
	if default_tax:
		default_tax=default_tax[0]
	else:
		default_tax=None
	#if control:
	#	ledger = control[0]['name']
	for customer in customers:
		billing_method = customer['billing_method']
		customer_billing_address=None
		if billing_method==info.BILLING_METHOD_TWO:#email
			customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer['person_id'] or customer['company_id'],info.CONTACT_TYPE_EMAIL])
		if billing_method==info.BILLING_METHOD_THREE:#fax
			customer_billing_address = db_tools.exec_action(dbc,'get_customer_billing_details',[customer['person_id'] or customer['company_id'],info.CONTACT_TYPE_FAX])
		if not customer_billing_address:
			customer['customer_billing_address'] = ''
		else:
			customer['customer_billing_address'] = customer_billing_address[0]['detail']
	page.content = {
		'invoicer':db_tools.exec_action(dbc,'get_invoicer')[0],
		'tax_list':tax_list,
		'default_tax':default_tax,
		'invoicer_address':utils.get_formatted_address(db_tools.exec_action(dbc, 'get_invoicer')[0],return_one_line=True),
		'METHOD_ONE':info.BILLING_METHOD_ONE,
		'METHOD_TWO':info.BILLING_METHOD_TWO,
		'METHOD_THREE':info.BILLING_METHOD_THREE,
		'customers':customers,
		'invoice_id':db_tools.exec_action(dbc, 'get_invoicer_id')[0]['invoice_id'],
		'today':datetime.date.today().isoformat(),
		'sales':db_tools.exec_action(dbc, 'get_sales_agents'),
		'sl':'ar',
		'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
	}	
	page.setup = {
		'breadcrumbs':['operations', 'New Invoice'],
		'menu_title':'Operations Portal',
		'menu':['invoice!','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'Create Invoice',
		'broadcast_message':broadcast_message,
		'template':'finance/fic.opt',
		'form':True,
		'javascript':True
	}
	page.info = {
		'query_string':info.query_string,
	}
	return page.render()

def create_invoice( req,**params ):
	"""actually create an invoice -- redirects to invoice list"""
	try:
		session = Session.Session(req)
		check_access(req,session, req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()	    
		var_map = {'p_customer_id':'','p_sales_agent_id':params['sales_agent_id'],'p_invoice_id':params['invoice_id'],'p_item_qty':'','p_item_description':'','p_item_unit_price':'','p_item_tax_ids':'','p_item_tax_inclusions':''}
		if params.has_key('customer_info') and params['customer_info']:#customer id
			var_map['p_customer_id'] = params['customer_info'].split('|')[1]
		else:
			util.redirect(req,"/bin/operations.py/insert_invoice?sl=%s" % params['sl'])
		total_amount = 0
		if type(params['description']) == type([]):
			for i in xrange(len(params['description'])):
				var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'][i])+'",'
				var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'][i])+'",'
				var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'][i])+'",'
				var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][i][:-1]+'",'
				var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][i][:-1]+'",'
			var_map['p_item_description'] = var_map['p_item_description'][:-1]
			var_map['p_item_qty'] = var_map['p_item_qty'][:-1]
			var_map['p_item_unit_price'] = var_map['p_item_unit_price'][:-1]
			var_map['p_item_tax_ids'] = var_map['p_item_tax_ids'][:-1]
			var_map['p_item_tax_inclusions'] = var_map['p_item_tax_inclusions'][:-1]
		else:
			var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'])+'"'
			var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'])+'"'
			var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'])+'"'
			var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][:-1]+'"'
			var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][:-1]+'"'
		result = db_tools.exec_action(dbc,'create_invoice',[var_map['p_customer_id'],var_map['p_sales_agent_id'],var_map['p_invoice_id'], params['invoice_date'], var_map['p_item_qty'],var_map['p_item_description'],var_map['p_item_unit_price'],var_map['p_item_tax_ids'],var_map['p_item_tax_inclusions']], nullify=True, escaped=True)[0]['create_invoice']
		conn.commit()
		result_desc = showErr(int(result))
		broadcast_message = result_desc
		util.redirect(req,"/bin/operations.py/show_invoice?sl=%s&broadcast_message=%s" % (params['sl'], broadcast_message))
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,"/bin/operations.py?broadcast_message=%s" % broadcast_message)

def show_invoice( req,**params ):
	"""displays a list of invoice links"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
	invoiceset = db_tools.exec_action(dbc,'get_invoices')		
	for invoice in invoiceset:
		invoice['date'] = str(invoice['date'])[:10]
	control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0] # what's this for?
	ledger = control['name'] # and this?
	page.content = {
		'invoiceset':invoiceset
	}
	page.setup = {
		'breadcrumbs':['operations', 'Invoices'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'Search',
		'broadcast_message':broadcast_message,
		'template':'finance/fis.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()

def show_purchase_order( req,**params ):
	"""displays a list of purchase orders"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
	purchase_order_sets = db_tools.exec_action(dbc,'get_purchase_orders')	
	for purchase_order in purchase_order_sets:
		purchase_order['date'] = str(purchase_order['date'])[:10]
	control = db_tools.exec_action(dbc,'get_coa2',[params['sl']])[0]		
	ledger = control['name']
	page.content = {
		'purchase_order_sets':purchase_order_sets
	}
	page.setup = {
		'breadcrumbs':['operations', 'Purchase Orders'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
		'content_title':'Search',
		'broadcast_message':broadcast_message,
		'template':'finance/fps.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()

def insert_purchase_order( req,**params ):
	"""displays a form for creating a purchase order"""
	import datetime
	page = Page(req, company_db=True)
	session = page.session
	dbc = page.company_db.cursor()
	broadcast_message = params.has_key('broadcast_message') and params['broadcast_message'] or ''
	#check the 'ap' account
	control = db_tools.exec_action(dbc,'get_coa2',['ap'])
	if not control:
		if broadcast_message:
			broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/insert_account?short_name=ap'>create</a> an Account(finance) with Subledger 'ap'." or "<br />You must create an Account(finance) with Subledger 'ap'."
		else:
			broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/insert_account?short_name=ap'>create</a> an Account(finance) with Subledger 'ap'." or "You must create an Account(finance) with Subledger 'ap'."
	#check supplier
	suppliers = db_tools.exec_action(dbc,'get_suppliers')
	if not suppliers:
		if broadcast_message:
			broadcast_message += "<br />You must <a href='/bin/operations.py/create_supplier_entity_type'>create</a> some suppliers before you create a purchase order."
		else:
			broadcast_message = "You must <a href='/bin/operations.py/create_supplier_entity_type'>create</a> some suppliers before you create a purchase order."
	#check equip account
	equip_account = db_tools.exec_action(dbc,'get_equip_account')
	baccounts = db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['EXPENSE'])
	if not equip_account and not baccounts:
		if broadcast_message:
			broadcast_message += 'finance' in session['user_access'].values() and "<br />You must <a href='/bin/finance.py/insert_account?account_type_id=EXPENSE'>create</a> an Account(finance) with type 'EXPENSE' and without Subledger or <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Capital Equipment)(finance)." or "<br />You must create some Accounts(finance) with type 'EXPENSE' and without Subledger or setup the Special accounts(Capital Equipment)(finance)."			
		else:
			broadcast_message += 'finance' in session['user_access'].values() and "You must <a href='/bin/finance.py/insert_account?account_type_id=EXPENSE'>create</a> an Account(finance) with type 'EXPENSE' and without Subledger or <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Special accounts(Capital Equipment)(finance)." or "You must create some Accounts(finance) with type 'EXPENSE' and without Subledger or setup the Special accounts(Capital Equipment)(finance)."
	if not control or not suppliers or (not equip_account and not baccounts):
		util.redirect(req,"/bin/operations.py?broadcast_message=%s"%broadcast_message)
	#check tax list,default tax,equip account
	default_taxes = db_tools.exec_action(dbc,'get_default_tax')	
	taxes = db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail purchase'])	
	if not taxes:
		if broadcast_message:
			broadcast_message += 'finance' in session['user_access'].values() and "<br />You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order." or "<br />You'd better setup the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order."
		else:
			broadcast_message += 'finance' in session['user_access'].values() and "You'd better <a href='/bin/finance.py/special_params_setting_page'>setup</a> the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order." or "You'd better setup the Tax accounts(Retail Purcharse)(finance) before you create a Purcharse Order."			
	if not default_taxes:
		if broadcast_message:
			broadcast_message += 'admin' in session['user_access'].values() and "<br />You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create a Purcharse Order." or "<br />You'd better setup the Default Tax(admin) before you create a Purcharse Order."
		else:
			broadcast_message += 'admin' in session['user_access'].values() and "You'd better <a href='/bin/admin.py/insert_transaction_tax'>setup</a> the Default Tax(admin) before you create a Purcharse Order." or "You'd better setup the Default Tax(admin) before you create a Purcharse Order."			
	buyer = db_tools.exec_action(dbc,'get_buyer')[0]
	if default_taxes:
		default_tax=default_taxes[0]
	else:
		default_tax=None
	#if control:
	#	ledger = control[0]['name']
	this_entity_id = db_tools.exec_action(dbc,'app_get_company_entity_id')[0]['code_value']
	page.content = {
		'buyer':buyer,
		'buyer_address':utils.get_formatted_address(buyer,return_one_line=True),
		'suppliers':suppliers,
		'delivery_address':db_tools.exec_action(dbc,'get_delivery_address',[this_entity_id]),
		'purchase_order_id':db_tools.exec_action(dbc, 'get_purchase_order_id')[0]['purchase_order_id'],
   		'today':datetime.date.today().isoformat(),
		'taxes':taxes,
		'tax_counter':len(taxes),
		'sl':'ap',
		'default_tax':default_tax,
		'baccounts':baccounts,
		'equip_account':equip_account,
		'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
	}
	page.setup = {
		'breadcrumbs':['operations', 'Create Purchase Order'],
		'broadcast_message':broadcast_message,
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder!','billpayment','spacer','newsupplier'],
		'content_title':'Create Purchase Order',
		'template':'finance/fpc.opt',
		'form':True,
		'javascript':True
	}
	page.info = {
		'query_string':info.query_string,
		#'ledger':ledger
	}
	return page.render()

def create_purchase_order( req,**params ):
	"""actually create a purchase order -- redirects to purchase order list"""
	try:
		session = Session.Session(req)
		check_access(req,session, req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()
		var_map = {'p_supplier_id':'','p_purchase_order_id':params['purchase_order_id'],'p_delivery_location_id':'','p_expense_account_id':'','p_item_qty':'','p_item_description':'','p_item_unit_price':'','p_item_tax_ids':'','p_item_tax_inclusions':''}
		if params.has_key('supplier_info') and params['supplier_info']:#customer id
			var_map['p_supplier_id'] = params['supplier_info'].split('|')[8]
		else:
			util.redirect(req,"/bin/operations.py/insert_purchase_order?sl=%s" % params['sl'])
		if params.has_key('balance_account') and params['balance_account']:
			var_map['p_expense_account_id'] = params['balance_account']
		else:
			util.redirect(req,"/bin/operations.py/insert_purchase_order?sl=%s" % params['sl'])
		if params.has_key('delivery_address') and params['delivery_address']:
			var_map['p_delivery_location_id'] = params['delivery_address'].split('|')[7]
		else:
			util.redirect(req,"/bin/operations.py/insert_purchase_order?sl=%s" % params['sl'])
		total_amount = 0
		if type(params['description']) == type([]):
			for i in xrange(len(params['description'])):
				var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'][i])+'",'
				var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'][i])+'",'
				var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'][i])+'",'
				var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][i][:-1]+'",'
				var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][i][:-1]+'",'
			var_map['p_item_description'] = var_map['p_item_description'][:-1]
			var_map['p_item_qty'] = var_map['p_item_qty'][:-1]
			var_map['p_item_unit_price'] = var_map['p_item_unit_price'][:-1]
			var_map['p_item_tax_ids'] = var_map['p_item_tax_ids'][:-1]
			var_map['p_item_tax_inclusions'] = var_map['p_item_tax_inclusions'][:-1]
		else:
			var_map['p_item_description'] += '"'+utils.escape_quotes_in_procedure(params['description'])+'"'
			var_map['p_item_qty'] += '"'+utils.escape_comma_in_number(params['qty'])+'"'
			var_map['p_item_unit_price'] += '"'+utils.escape_comma_in_number(params['unit_price'])+'"'
			var_map['p_item_tax_ids'] += '"'+params['tax_id_list'][:-1]+'"'
			var_map['p_item_tax_inclusions'] += '"'+params['tax_inclusions_list'][:-1]+'"'
		result = db_tools.exec_action(dbc,'create_purchase_order',[var_map['p_supplier_id'],var_map['p_purchase_order_id'],var_map['p_delivery_location_id'],var_map['p_expense_account_id'],params['purchase_order_date'],var_map['p_item_qty'],var_map['p_item_description'],var_map['p_item_unit_price'],var_map['p_item_tax_ids'],var_map['p_item_tax_inclusions']], nullify=True, escaped=True)[0]['create_purchase_order']
		conn.commit()
		result_desc = showErr(int(result))
		broadcast_message = result_desc
		broadcast_message += " <a href='/bin/operations.py/print_purchase_order?id=%s'>print purchase order</a>"%params['purchase_order_id']
		util.redirect(req,"/bin/operations.py/show_purchase_order?sl=%s&broadcast_message=%s" % (params['sl'], broadcast_message))
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,"/bin/operations.py?broadcast_message=%s" % broadcast_message)
	
def print_invoice(req, **params):
	"""displays an invoice in printer-friendly format"""
	page = Page(req, company_db=True, no_menu=True)
	dbc = page.company_db.cursor()
	import locale
	locale.setlocale(locale.LC_ALL,'')
	invoicer = db_tools.exec_action(dbc,'get_invoicer')[0]
	invoicer_address = utils.get_formatted_address(invoicer)
	if params.has_key('id'):
		invoices = db_tools.exec_action(dbc,'get_invoices1',[int(params['id'])])
	elif params.has_key('start_id'):
		invoices = db_tools.exec_action(dbc,'get_invoices2',[int(params['start_id'])])
	elif page.session.has_key('invoice_id_list'):
		invoices = db_tools.exec_action(dbc,'get_invoices3',[tuple(page.session.pop('invoice_id_list'))])
		page.session.save()
	for invoice in invoices:
		customer_info = db_tools.exec_action(dbc,'get_customer_by_id',[invoice['customer_id']])[0]
		if customer_info['billing_method']==info.BILLING_METHOD_ONE:
			address_details = db_tools.exec_action(dbc,'get_address_info',[invoice['address_id']])[0]
			invoice['address'] = utils.get_formatted_address(address_details)
		elif customer_info['billing_method']==info.BILLING_METHOD_TWO:
			invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])[0]['detail']
		elif customer_info['billing_method']==info.BILLING_METHOD_THREE:
			invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_FAX])[0]['detail']
		#TODO:BUG!!not only gst tax.
		invoice['items'] = db_tools.exec_action(dbc,'get_invoice_items_info',[int(invoice['id'])])			
		for item in invoice['items']:
			item['total_ex'] = locale.format('%.2f', round(utils.float_no_exception(item['total_ex']), 2), True)
			item['combined_tax'] = locale.format('%.2f', round(utils.float_no_exception(item['combined_tax']), 2), True)
			item['total_inc'] = locale.format('%.2f', round(utils.float_no_exception(item['total_inc']), 2), True)
		invoice['tax_aggregation'] = db_tools.exec_action(dbc, 'get_invoice_tax_aggregation', [int(invoice['id'])])
		if len(invoice['tax_aggregation']) == 1:
			invoice['tax_name'] = invoice['tax_aggregation'][0]['shortname']
		else:
			invoice['tax_name'] = 'Tax'
	remit_msgs = db_tools.exec_action(dbc,'get_remit_msg')
	page.content = {
		'invoicer_address':invoicer_address,
		'invoicer':invoicer,
		'invoices':invoices,
		'remit_msg':'<li>'+'</li><li>'.join([remit_msg['code_desc'] for remit_msg in remit_msgs]) + '</li>',
		'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],
	}
	page.setup = {
		'template':'finance/pi.opt'
	}
	return page.render()

def print_purchase_order( req,**params ):
	"""displays a purchase order in printer-friendly format"""
	page = Page(req, company_db=True, no_menu=True)
	dbc = page.company_db.cursor()
	import locale
	locale.setlocale(locale.LC_ALL,'')
	purchase_order_host = db_tools.exec_action(dbc,'get_buyer')[0]#TODO get_purchase_order
	purchase_order_address = utils.get_formatted_address(purchase_order_host)
	if params.has_key('id'):
		purchase_orders = db_tools.exec_action(dbc,'get_purchase_orders1',[int(params['id'])])
	else:
		purchase_orders = db_tools.exec_action(dbc,'get_purchase_orders2',[int(params['start_id'])])
	for purchase_order in purchase_orders:		
		address_details = db_tools.exec_action(dbc,'get_address_info',[purchase_order['address_id']])[0]
		delivery_address_details = db_tools.exec_action(dbc,'get_delivery_address_info',[purchase_order['delivery_location_id']])[0]
		delivery_address = utils.get_formatted_address(delivery_address_details)
		purchase_order['delivery_address_name'] = delivery_address_details['name']		
		purchase_order['delivery_address'] = delivery_address
		purchase_order['items'] = db_tools.exec_action(dbc,'get_purchase_order_items_info',[int(purchase_order['id'])])
		purchase_order['address'] = utils.get_formatted_address(address_details)
		for item in purchase_order['items']:
			item['total_ex'] = locale.format('%.2f', round(utils.float_no_exception(item['total_ex']), 2), True)
			item['combined_tax'] = locale.format('%.2f', round(utils.float_no_exception(item['combined_tax']), 2), True)
			item['total_inc'] = locale.format('%.2f', round(utils.float_no_exception(item['total_inc']), 2), True)
		purchase_order['tax_aggregation'] = db_tools.exec_action(dbc, 'get_po_tax_aggregation', [int(purchase_order['id'])])
		if len(purchase_order['tax_aggregation']) == 1:
			purchase_order['tax_name'] = purchase_order['tax_aggregation'][0]['shortname']
		else:
			purchase_order['tax_name'] = 'Tax'
	page.content = {
		'purchase_order_address':purchase_order_address,
		'purchase_order_host':purchase_order_host,
		'purchase_orders':purchase_orders,
		'abn_label': db_tools.exec_action(dbc,'get_sys_code',[info.BUSINESS_NUM_LABEL])[0]['code_value'],		
	}
	page.setup = {
		'template':'finance/pp.opt'
	}
	return page.render()

def payment_list_page(req,**params):
	"""displays a form for creating a receipt"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	import datetime
	page.content = {
		'today':datetime.date.today().isoformat(),
		'customers':db_tools.exec_action(dbc,'get_customers'),
		#TODO:add date condition to select all invoices which have not paid yet.
		'invoice_list':db_tools.exec_action(dbc,'get_all_invoices'),
		'skin':page.session['skin']
	}
	page.setup = {
		'breadcrumbs':['operations', 'Issue Receipt'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt!','spacer','newcustomer','spacer','porder','billpayment','spacer','newsupplier'],
		'broadcast_message': params.has_key('broadcast_message') and params['broadcast_message'] or None,
		'content_title':'Issue Receipt',
		'template':'operations/opl.opt',
		'form':True,
		'javascript':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()

def create_receive_payment(req, **params):
	"""actually creates a receipt -- redirects to receipt form"""
	try:
		session = Session.Session(req)
		check_access(req,session, req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()	    
		var_map = {'p_receipt_id':'','p_customer_id':params['customer'], 'p_amount':utils.escape_comma_in_number(params['amount']), 'p_comment':params['comment'],'p_invoice_ids':''}
		if type(params['invoice_id']) == list:
			for i in xrange(len(params['invoice_id'])):
				var_map['p_invoice_ids'] += '"'+params['invoice_id'][i]+'",'
			var_map['p_invoice_ids'] = var_map['p_invoice_ids'][:-1]
		else:
			var_map['p_invoice_ids'] += '"'+params['invoice_id']+'"'
		result = db_tools.exec_action(dbc,'generate_receipt', [var_map['p_receipt_id'],var_map['p_customer_id'],params['receipt_date'],var_map['p_amount'],var_map['p_comment'],var_map['p_invoice_ids']], True)[0]['generate_receipt']
		conn.commit()
		broadcast_message = showErr(int(result))
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,'/bin/operations.py/payment_list_page?broadcast_message=%s' % broadcast_message)

def bill_payment_page( req,**params ):
	'''diplays a form for recording a bill payment'''
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	import datetime
	page.content = {
		'today':datetime.date.today().isoformat(),
		#TODO:add date condition
		'suppliers':db_tools.exec_action(dbc,'get_suppliers'),
		'purchase_order_list':db_tools.exec_action(dbc,'get_all_purchase_orders'),
		'expense_accounts':db_tools.exec_action(dbc,'get_same_type_accounts', ['EXPENSE']),
		'all_expense_taxes':db_tools.exec_action(dbc, 'get_same_type_taxes', ['retail purchase']),
		'tax_aggregation':db_tools.exec_action(dbc, 'get_all_purchase_tax_aggregation'),
		'expenses_accounts':db_tools.exec_action(dbc,'get_accounts_by_type_without_sub',['EXPENSE']),
		'skin':page.session['skin']
	}
	page.setup = {
		'breadcrumbs':['operations', 'Bill Payment'],
		'menu_title':'Operations Portal',
		'menu':['invoice','receipt','spacer','newcustomer','spacer','porder','billpayment!','spacer','newsupplier'],
		'broadcast_message': params.has_key('broadcast_message') and params['broadcast_message'] or None,
		'content_title':'Bill Payment',
		'template':'operations/obp.opt',
		'form':True,
		'javascript':True,
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()

def pay_bill( req,**params ):
	"""actually pay a bill -- redirects to bill payment list"""
	try:
		session = Session.Session(req)
		check_access(req,session, req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()	    
		var_map = {'p_supplier_id':params['supplier_id'],'p_amount':utils.escape_comma_in_number(params['amount']),'p_tax_id':'','p_tax_amount':'','p_comment':utils.escape_quotes_in_sql(params['comment']),'p_adjustment_expense_account':params['adjustment_expense_account'],'p_adjustment_comment':utils.escape_quotes_in_sql(params['adjustment_comment']), 'p_purchase_order_ids':''}
		if type(params['tax_id']) == list:
			for i in xrange(len(params['tax_id'])):
				var_map['p_tax_id'] += '"'+params['tax_id'][i]+'",'
				var_map['p_tax_amount'] += '"'+utils.escape_comma_in_number(params['tax_amount'][i])+'",'
			var_map['p_tax_id'] = var_map['p_tax_id'][:-1]
			var_map['p_tax_amount'] = var_map['p_tax_amount'][:-1]
		else:
			var_map['p_tax_id'] += '"'+params['tax_id']+'"'
			var_map['p_tax_amount'] += '"'+utils.escape_comma_in_number(params['tax_amount'])+'"'
		if type(params['purchase_order_ids']) == list:
			for i in xrange(len(params['purchase_order_ids'])):
				var_map['p_purchase_order_ids'] += '"'+params['purchase_order_ids'][i]+'",'
			var_map['p_purchase_order_ids'] = var_map['p_purchase_order_ids'][:-1]
		else:
			var_map['p_purchase_order_ids'] += '"'+params['purchase_order_ids']+'"'
		result = db_tools.exec_action(dbc,'pay_bill',[var_map['p_supplier_id'],params['payment_date'],var_map['p_amount'], var_map['p_tax_id'],var_map['p_tax_amount'],var_map['p_comment'],var_map['p_adjustment_expense_account'],var_map['p_adjustment_comment'],var_map['p_purchase_order_ids']], escaped = True)[0]['pay_bill']
		conn.commit()
		result_desc = showErr(int(result))
		broadcast_message = result_desc
		util.redirect(req,"/bin/operations.py/bill_payment_page?broadcast_message=%s" % broadcast_message)
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,"/bin/operations.py?broadcast_message=%s" % broadcast_message)

def send_invoice( req,**params ):
	"""emails an invoice to a customer"""
	try:		
		session = Session.Session(req)
		check_access(req,session, req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()
		customer_id = params['customer_id']
		customer_info = db_tools.exec_action(dbc,'get_customer_by_id', [customer_id])
		if customer_info:
			customer_info = customer_info[0]
		else:
			raise genErrorPage('customer_not_exist','/bin/login.py/login_out')
		invoice_ids = params['invoiceId']
		billing_method = customer_info['billing_method']
		if billing_method==info.BILLING_METHOD_ONE:
			if type(invoice_ids) == list:
				invoice_id_list = []
				for invoice_id in invoice_ids:
					db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_id,billing_method,customer_info['address_id']])
					invoice_id_list.append(invoice_id)
				conn.commit()
				session['invoice_id_list'] = invoice_id_list
				session.save()
				util.redirect(req,"/bin/operations.py/print_invoice")
			else:
				db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_ids,billing_method,customer_info['address_id']])
				conn.commit()
				util.redirect(req,"/bin/operations.py/print_invoice?id=%s"%invoice_ids)
		elif billing_method==info.BILLING_METHOD_TWO:#email			
			if type(invoice_ids) == list:
				invoice_file_list = []
				import os
				for invoice_id in invoice_ids:
					invoice_content = create_invoice_file_content(req,session=session,id=invoice_id)
					invoice_file_name = "invoice_file_%s.html"%str(invoice_id)
					save_path=os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH)
					save_file_path = os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH,invoice_file_name)
					utils.save_upload_file(save_path,save_file_path, invoice_content)
					invoice_file_list.append(save_file_path)
			else:
				invoice_file_list = []
				import os
				invoice_content = create_invoice_file_content(req,session=session,id=invoice_ids)
				invoice_file_name = "invoice_file_%s.html"%str(invoice_ids)
				save_path=os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH)
				save_file_path = os.path.join(info.basic_save_path,info.INVOICE_FILE_PATH,invoice_file_name)
				utils.save_upload_file(save_path, save_file_path, invoice_content)		
				invoice_file_list.append(save_file_path)
			detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
			if detail:
				detail=detail[0]['detail']
			else:
				raise genErrorPage('BILLING_METHOD_ERROR')		
			#set the email			
			to_email=[]
			to_email.append(detail)
			subject="invoice list"
			email_content=""
			files=invoice_file_list
			auth_required=True
			#smtp server setting
			smtp_server_set={}
			for code_id in [info.THIS_EMAIL,info.SMTP_SERVER,info.SMTP_USER,info.SMTP_PASS]:
				code_value = db_tools.exec_action(dbc,'get_sys_code', [code_id])
				if not code_value:
					raise genErrorPage('SMTP_ERROR',req.uri)
				else:
					smtp_server_set[code_id] = code_value[0]['code_value']
			#send it
			user_email.send_mail(send_from = smtp_server_set[info.THIS_EMAIL],send_to = to_email,subject = subject,text = email_content,files = files,server=smtp_server_set[info.SMTP_SERVER],auth_required = auth_required,smtp_user = smtp_server_set[info.SMTP_USER],smtp_pass = smtp_server_set[info.SMTP_PASS])
			#record it
			
			if type(invoice_ids) == list:				
				for invoice_id in invoice_ids:					
					db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
			else:				
				db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
			conn.commit()
			#return
			broadcast_message = 'The invoice has been sent'

		elif billing_method==info.BILLING_METHOD_THREE:#fax
			#send invoice
			if type(invoice_ids) == list:
				pass
			else:
				pass
			#record it
			detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_FAX])
			if detail:
				detail=detail[0]['detail']
			else:
				detail=''
			if type(invoice_ids) == list:				
				for invoice_id in invoice_ids:					
					db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
			else:				
				db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
			conn.commit()
			#return
			broadcast_message = 'The invoice has been sent'

##					invoice_file_url = print_invoice
##					detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
##					invoice_file_list.append(invoice_file_url)
##				conn.commit()
##				session['invoice_id_list'] = invoice_id_list
##				session.save()
##				util.redirect(req,"/bin/operations.py/print_invoice")
##			else:
##				detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
##				conn.commit()
##				util.redirect(req,"/bin/operations.py/print_invoice?id=%s"%invoice_ids)
				
##		if type(invoice_ids) == list:
##			for invoice_id in invoice_ids:
##				#do something
##				#1:get the billing_method in the customer table
##				customer_info = db_tools.exec_action(dbc,'get_customer_by_invoice_id', [invoice_id])
##				if not customer_info:
##					raise GeneralBusinessErr('SYSTEM_ERROR','/bin/login.py/login_out')
##				else:
##					customer_info = customer_info[0]
##				billing_method = customer_info['billing_method']
##				#'get_customer_by_invoice_id':"SELECT * FROM customer c,system.invoice_info ii WHERE c.id=ii.customer_id AND ii.invoice_id=%s"			
##				#2:send the invoice
##				if billing_method==info.BILLING_METHOD_ONE:#hard copy
##					#print invoice
##					db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_id,billing_method,customer_info['address_id']])					
##				if billing_method==info.BILLING_METHOD_TWO:#email
##					detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
##					if detail:
##						detail=detail[0]['detail']
##					else:
##						detail=''
##					#email invoice
##					db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
##				if billing_method==info.BILLING_METHOD_THREE:#fax
##					detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_FAX])
##					if detail:
##						detail=detail[0]['detail']
##					else:
##						detail=''
##					#fax invoice
##					db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_id,billing_method,detail])
##			conn.commit()
##		else:
##			customer_info = db_tools.exec_action(dbc,'get_customer_by_invoice_id', [invoice_ids])
##			if not customer_info:
##				raise GeneralBusinessErr('SYSTEM_ERROR','/bin/login.py/login_out')
##			else:
##				customer_info = customer_info[0]
##			billing_method = customer_info['billing_method']
##			if billing_method==info.BILLING_METHOD_ONE:#hard copy
##				#print invoice
##				db_tools.exec_action(dbc,'insert_invoice_delivery_report1', [invoice_ids,billing_method,customer_info['address_id']])					
##			if billing_method==info.BILLING_METHOD_TWO:#email
##				detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])
##				if detail:
##					detail=detail[0]['detail']
##				else:
##					detail=''
##				#email invoice
##				db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
##			if billing_method==info.BILLING_METHOD_THREE:#fax
##				detail = db_tools.exec_action(dbc,'get_customer_billing_details', [customer_info['entity_id'],info.CONTACT_TYPE_FAX])
##				if detail:
##					detail=detail[0]['detail']
##				else:
##					detail=''
##				#fax invoice
##				db_tools.exec_action(dbc,'insert_invoice_delivery_report2', [invoice_ids,billing_method,detail])
##			conn.commit()
##		broadcast_message = 'The invoice sent'
##		util.redirect(req,'/bin/operations.py/show_invoice?sl=ar&amp;broadcast_message=%s'%broadcast_message)
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,'/bin/operations.py/customer_page?cid=%s&amp;broadcast_message=%s'%(customer_id,broadcast_message))
		
def create_invoice_file_content(req,**params):
	"""displays an invoice in printer-friendly format"""
	#page = Page(req, company_db=True, no_menu=True)
	#dbc = page.company_db.cursor()
	session=params['session']
	dbc=get_connection(session).cursor()
	import locale
	locale.setlocale(locale.LC_ALL,'')
	invoicer = db_tools.exec_action(dbc,'get_invoicer')[0]
	invoicer_address = utils.get_formatted_address(invoicer)
	if params.has_key('id'):
		invoices = db_tools.exec_action(dbc,'get_invoices1',[int(params['id'])])	
	for invoice in invoices:
		customer_info = db_tools.exec_action(dbc,'get_customer_by_id',[invoice['customer_id']])[0]
		if customer_info['billing_method']==info.BILLING_METHOD_ONE:
			address_details = db_tools.exec_action(dbc,'get_address_info',[invoice['address_id']])[0]
			invoice['address'] = utils.get_formatted_address(address_details)
		elif customer_info['billing_method']==info.BILLING_METHOD_TWO:
			invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_EMAIL])[0]['detail']
		elif customer_info['billing_method']==info.BILLING_METHOD_THREE:
			invoice['address'] = db_tools.exec_action(dbc,'get_customer_billing_details',[customer_info['entity_id'],info.CONTACT_TYPE_FAX])[0]['detail']
		#TODO:BUG!!not only gst tax.
		invoice['items'] = db_tools.exec_action(dbc,'get_invoice_items_info',[int(invoice['id'])])			
		for item in invoice['items']:
			item['total_ex'] = locale.format('%.2f', round(utils.float_no_exception(item['total_ex']), 2), True)
			item['combined_tax'] = locale.format('%.2f', round(utils.float_no_exception(item['combined_tax']), 2), True)
			item['total_inc'] = locale.format('%.2f', round(utils.float_no_exception(item['total_inc']), 2), True)
		invoice['tax_aggregation'] = db_tools.exec_action(dbc, 'get_invoice_tax_aggregation', [int(invoice['id'])])
		if len(invoice['tax_aggregation']) == 1:
			invoice['tax_name'] = invoice['tax_aggregation'][0]['shortname']
		else:
			invoice['tax_name'] = 'Tax'
	remit_msgs = db_tools.exec_action(dbc,'get_remit_msg')
	content = {
		'invoicer_address':invoicer_address,
		'invoicer':invoicer,
		'invoices':invoices,
		'remit_msg':'<li>'+'</li><li>'.join([remit_msg['code_desc'] for remit_msg in remit_msgs]) + '</li>'
	}
	from phunc.template import Template
	template = Template()
	template.parseFile(get_template_dir(req) + 'finance/pi.opt')
	html = template.render(content)
	return html
